import { useState, useEffect } from 'react'
import { motion } from 'framer-motion'
import TrainingPanel from '../components/TrainingPanel'
import ProgressMonitor from '../components/ProgressMonitor'
import AssessmentPanel from '../components/AssessmentPanel'
import MockExamPanel from '../components/MockExamPanel'
import DailyLearningPanel from '../components/DailyLearningPanel'
import OnboardingGuide from '../components/OnboardingGuide'
import DebatePanel from '../components/DebatePanel'
import { userStatusApi } from '../services/api'
import './TrainingWorkspace.css'

const TrainingWorkspace = () => {
  const [activeTab, setActiveTab] = useState<'training' | 'progress' | 'assessment' | 'mock-exam' | 'daily-learning' | 'debate'>('daily-learning')
  const [userId] = useState('user_001') // 临时用户ID，后续从认证获取
  const [activePlanId, setActivePlanId] = useState<string | null>(null) // 当前激活的计划ID
  const [userStatus, setUserStatus] = useState<any>(null) // 用户状态
  const [isLoadingStatus, setIsLoadingStatus] = useState(true)

  // 加载用户状态
  useEffect(() => {
    loadUserStatus()
  }, [userId])

  const loadUserStatus = async () => {
    console.log('🟢 [TrainingWorkspace] 开始加载用户状态，userId:', userId)
    setIsLoadingStatus(true)
    try {
      const status = await userStatusApi.getUserStatus(userId)
      console.log('🟢 [TrainingWorkspace] 用户状态加载成功:', status)
      setUserStatus(status)
      
      // 根据状态设置默认标签页和计划ID
      const statusData = status as any
      console.log('🟢 [TrainingWorkspace] 用户状态数据:', {
        current_stage: statusData.current_stage,
        has_plan: statusData.has_plan,
        plan_id: statusData.plan_id
      })
      if (statusData.plan_id) {
        setActivePlanId(statusData.plan_id)
      }
      
      // 首次访问，引导到测试
      if (statusData.current_stage === 'first_visit') {
        setActiveTab('mock-exam')
      }
    } catch (error) {
      console.error('❌ [TrainingWorkspace] 加载用户状态失败:', error)
    } finally {
      setIsLoadingStatus(false)
      console.log('🟢 [TrainingWorkspace] 用户状态加载完成')
    }
  }

  return (
    <div className="training-workspace">
      {/* 顶部导航栏 */}
      <header className="workspace-header">
        <div className="header-content">
          <h1 className="app-title">AI法考备考软件</h1>
          <nav className="workspace-nav">
            <button
              className={`nav-button ${activeTab === 'training' ? 'active' : ''}`}
              onClick={() => setActiveTab('training')}
            >
              训练工作台
            </button>
            <button
              className={`nav-button ${activeTab === 'progress' ? 'active' : ''}`}
              onClick={() => setActiveTab('progress')}
            >
              进度监控
            </button>
            <button
              className={`nav-button ${activeTab === 'assessment' ? 'active' : ''}`}
              onClick={() => setActiveTab('assessment')}
            >
              评估诊断
            </button>
            <button
              className={`nav-button ${activeTab === 'mock-exam' ? 'active' : ''}`}
              onClick={() => setActiveTab('mock-exam')}
            >
              模拟测试
            </button>
            <button
              className={`nav-button ${activeTab === 'daily-learning' ? 'active' : ''}`}
              onClick={() => setActiveTab('daily-learning')}
            >
              每日学习
            </button>
            <button
              className={`nav-button ${activeTab === 'debate' ? 'active' : ''}`}
              onClick={() => setActiveTab('debate')}
            >
              辩论训练
            </button>
          </nav>
        </div>
      </header>

      {/* 主内容区 */}
      <main className="workspace-main">
        {isLoadingStatus ? (
          <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', minHeight: '60vh', flexDirection: 'column', gap: '1rem' }}>
            <div className="loading-spinner" style={{ width: '50px', height: '50px', border: '4px solid #f0f0f0', borderTopColor: '#667eea', borderRadius: '50%', animation: 'spin 1s linear infinite' }}></div>
            <p>加载中...</p>
          </div>
        ) : (
          <motion.div
            key={activeTab}
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.3 }}
            className="workspace-content"
          >
            {/* 首次访问引导 */}
            {userStatus && (userStatus as any).current_stage === 'first_visit' && activeTab === 'mock-exam' && (
              <OnboardingGuide
                userId={userId}
                onTestStart={() => {
                  // 测试开始，显示测试面板
                }}
                onTestComplete={async () => {
                  // 测试完成，更新状态并引导创建计划
                  await loadUserStatus()
                  setActiveTab('assessment')
                }}
              />
            )}
            
            {activeTab === 'training' && (
            <TrainingPanel 
              userId={userId} 
              onNavigate={(tab) => setActiveTab(tab as any)}
            />
          )}
            {activeTab === 'progress' && <ProgressMonitor userId={userId} />}
            {activeTab === 'assessment' && (
              <AssessmentPanel
                userId={userId}
                onPlanCreated={async (planId) => {
                  setActivePlanId(planId)
                  await loadUserStatus() // 重新加载状态
                  setActiveTab('daily-learning')
                }}
              />
            )}
            {activeTab === 'mock-exam' && (
              <MockExamPanel
                userId={userId}
                onNavigateToPlan={async () => {
                  await loadUserStatus() // 重新加载状态
                  setActiveTab('assessment') // 导航到评估诊断页面
                }}
                onTestComplete={async () => {
                  await loadUserStatus() // 重新加载状态
                  // 测试完成后，如果还没有计划，引导到评估诊断页面
                  const status = await userStatusApi.getUserStatus(userId)
                  const statusData = status as any
                  if (!statusData.has_plan) {
                    setActiveTab('assessment') // 导航到评估诊断页面创建计划
                  }
                }}
              />
            )}
            {activeTab === 'daily-learning' && (
              <DailyLearningPanel 
                userId={userId} 
                planId={activePlanId || undefined}
                userStatus={userStatus}
                onPlanCreated={async (planId) => {
                  console.log('🟢 [TrainingWorkspace] onPlanCreated回调被触发，planId:', planId)
                  console.log('🟢 [TrainingWorkspace] 当前userStatus:', userStatus)
                  setActivePlanId(planId)
                  // 延迟加载用户状态，避免立即覆盖forceShowQuestions
                  setTimeout(async () => {
                    await loadUserStatus()
                    console.log('🟢 [TrainingWorkspace] 用户状态已重新加载')
                  }, 500)
                }}
                onNavigate={(tab) => {
                  console.log('🟢 [TrainingWorkspace] 导航请求:', tab)
                  setActiveTab(tab as any)
                }}
              />
            )}
            {activeTab === 'debate' && (
              <DebatePanel 
                userId={userId}
                onNavigate={(tab) => setActiveTab(tab as any)}
              />
            )}
          </motion.div>
        )}
      </main>
    </div>
  )
}

export default TrainingWorkspace

